import { useEffect, useState } from 'react';
import styles from './index.less';
import { Modal, Form, Input, Select, InputNumber } from 'antd';
import { IData, IProps, IGoodsType, IResponse } from './type';
import request from 'umi-request';
import { modifyGetData } from '@/service/goods';
import store from '@/store';

export default function SaleForm(props: IProps) {
  // 组件需要使用到的变量
  const [normsList, setNormsList] = useState<IGoodsType[]>([]);
  const [selectList, setSelectList] = useState<IGoodsType[]>([]);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [form] = Form.useForm()
  const {getGoodsNorms, getGoodsType} = store

  const handleOk = () => {};

  // 点击取消时关闭新增或修改弹框
  const handleCancel = (): void => {
    props.handleCancel();
    form.resetFields()
  };

  const handleChange = () => {};

  // 修改和增加弹框的共用方法
  const otherModifyOrAdd = (url: string, data?: IData) => {
    setConfirmLoading(true);
    request.post(url, { data }).then(async(res: IResponse) => {
      if (res && res.code == 200) {
        await props.getFormData();
      }
      handleCancel();
      form.resetFields()
      setConfirmLoading(false)
    })
  };

  // 数据全部填入并提交时的回调
  const onFinish = (values: IData): void => {
    const { selectKey } = props;
    // 如果修改时，调用修改接口并传入参数
    if (selectKey) {
      otherModifyOrAdd('/modify', {
        ...values,
        selectKey,
      });
    } else {
      // 如果新增时，调用新增接口并传入参数
      otherModifyOrAdd('/addGoods', values);
    }
    
  };

  const onFinishFailed = () => {};


  useEffect(() => {
    // 商品规格
    getGoodsNorms().then((res: IResponse | undefined) => {
      setNormsList(res!.data as IGoodsType[])
    })

    // 商品类别
    getGoodsType().then((res: IResponse | undefined) => {
      setSelectList(res!.data as IGoodsType[])
    })
  }, []);

  useEffect(() => {
    const { selectKey } = props;
    if (selectKey === null) {
      form.resetFields()
    }else {
      props.visible && modifyGetData({selectKey}).then((res: IResponse) => {
        if(res && res.code == 200) {
          const { goodsCode, goodsName, norms, goodsType, unit } = res.data as IData
          const goodsObj = { goodsCode, goodsName, norms, goodsType, unit }
          form.setFieldsValue(goodsObj)
        }
      })
    }
  }, [props.visible]);

  const { selectKey } = props;
  const { Option } = Select;

  return (
    <>
      <Modal
        title={`${selectKey ? '修改' : '新增'}商品`}
        visible={props.visible}
        onOk={() => form.submit()}
        onCancel={handleCancel}
        destroyOnClose
        okText="确定"
        cancelText="取消"
        confirmLoading={confirmLoading}
        forceRender
        maskClosable={false}
      >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            form={form}
          >
            <Form.Item
              label="商品编码"
              name="goodsCode"
              rules={[{ required: true, message: '请输入商品编码' }]}
              className={styles.formItem}
            >
              <Input placeholder="请输入商品编码" />
            </Form.Item>
            <Form.Item
              label="商品名称"
              name="goodsName"
              rules={[{ required: true, message: '请输入商品名称' }]}
              className={styles.formItem}
            >
              <Input placeholder="请输入商品名称" />
            </Form.Item>
            <Form.Item
              label="商品规格"
              name="norms"
              rules={[{ required: true, message: '请输入商品规格' }]}
              className={styles.formItem}
            >
              <Select placeholder="请选择商品规格" onChange={handleChange}>
                {normsList.map((item: IGoodsType) => {
                  return (
                    <Option value={item.type} key={item.id}>
                      {item.type}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="商品类别"
              name="goodsType"
              rules={[{ required: true, message: '请输入商品类别' }]}
              className={styles.formItem}
            >
              <Select placeholder="请选择商品类别" onChange={handleChange}>
                {selectList.map((item: IGoodsType) => {
                  return (
                    <Option value={item.type} key={item.id}>
                      {item.type}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="商品单价"
              name="unit"
              rules={[{ required: true, message: '请输入商品单价' }]}
              className={styles.formItem}
            >
              <InputNumber placeholder="请输入商品单价" />
            </Form.Item>
          </Form>
      </Modal>
    </>
  );
}
